#!/bin/bash

# Third-Party Add-on Compatibility Analysis Script
# Analyzes ingress-nginx, NVIDIA GPU device plugin, and NodeLocal DNSCache compatibility
# during EKS upgrade process

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Print functions
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_compatible() {
    echo -e "${GREEN}[✅ COMPATIBLE]${NC} $1"
}

print_upgrade_required() {
    echo -e "${RED}[❌ UPGRADE_REQUIRED]${NC} $1"
}

print_upgrade_recommended() {
    echo -e "${YELLOW}[⚠️ UPGRADE_RECOMMENDED]${NC} $1"
}

# Function to show usage
show_usage() {
    cat << EOF
Usage: $0 -c CLUSTER_NAME -r REGION -t TARGET_EKS_VERSION [OPTIONS]

Required:
  -c, --cluster     EKS cluster name
  -r, --region      AWS region
  -t, --target      Target EKS version (e.g., 1.28, 1.29, 1.30)

Optional:
  -p, --path        Upgrade path (comma-separated versions, e.g., "1.27,1.28,1.29,1.30")
  -f, --format      Output format: text|json|yaml (default: text)
  -o, --output      Output directory (default: ./third-party-analysis-TIMESTAMP)
  -v, --verbose     Verbose output
  --aws-profile     AWS profile to use
  -h, --help        Show this help message

Examples:
  $0 -c my-cluster -r us-east-1 -t 1.30
  $0 -c my-cluster -r us-east-1 -p "1.27,1.28,1.29,1.30" -f json
  $0 -c my-cluster -r us-east-1 -t 1.30 --aws-profile production
  $0 --show-sources  # Show compatibility data sources and limitations

Description:
This script analyzes third-party add-on compatibility during EKS upgrades:
- ingress-nginx: Kubernetes Ingress controller
- NVIDIA GPU device plugin: GPU resource management
- NodeLocal DNSCache: Node-local DNS caching

IMPORTANT: Compatibility data is based on manual research and conservative estimates.
Always verify in test environment before production use. Use --show-sources for details.

EOF
}

# Parse command line arguments
CLUSTER_NAME=""
REGION=""
TARGET_VERSION=""
UPGRADE_PATH=""
FORMAT="text"
OUTPUT_DIR=""
VERBOSE=false
AWS_PROFILE=""

while [[ $# -gt 0 ]]; do
    case $1 in
        -c|--cluster)
            CLUSTER_NAME="$2"
            shift 2
            ;;
        -r|--region)
            REGION="$2"
            shift 2
            ;;
        -t|--target)
            TARGET_VERSION="$2"
            shift 2
            ;;
        -p|--path)
            UPGRADE_PATH="$2"
            shift 2
            ;;
        -f|--format)
            FORMAT="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT_DIR="$2"
            shift 2
            ;;
        -v|--verbose)
            VERBOSE=true
            shift
            ;;
        --aws-profile)
            AWS_PROFILE="$2"
            shift 2
            ;;
        -h|--help)
            show_usage
            exit 0
            ;;
        *)
            echo "Unknown option $1"
            show_usage
            exit 1
            ;;
    esac
done

# Validate required parameters
if [[ -z "$CLUSTER_NAME" || -z "$REGION" ]]; then
    print_error "Cluster name and region are required"
    show_usage
    exit 1
fi

if [[ -z "$TARGET_VERSION" && -z "$UPGRADE_PATH" ]]; then
    print_error "Either target version (-t) or upgrade path (-p) is required"
    show_usage
    exit 1
fi

# Set default output directory
if [[ -z "$OUTPUT_DIR" ]]; then
    OUTPUT_DIR="./third-party-analysis-$(date +%Y%m%d-%H%M%S)"
fi

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Set AWS profile if provided
if [[ -n "$AWS_PROFILE" ]]; then
    export AWS_PROFILE="$AWS_PROFILE"
fi

print_info "Starting third-party add-on compatibility analysis"
print_info "Cluster: $CLUSTER_NAME"
print_info "Region: $REGION"
if [[ -n "$TARGET_VERSION" ]]; then
    print_info "Target EKS Version: $TARGET_VERSION"
fi
if [[ -n "$UPGRADE_PATH" ]]; then
    print_info "Upgrade Path: $UPGRADE_PATH"
fi
print_info "Output Directory: $OUTPUT_DIR"

# Initialize results
RESULTS_FILE="$OUTPUT_DIR/third-party-compatibility.json"
echo '{"timestamp":"'$(date -Iseconds)'","cluster":"'$CLUSTER_NAME'","region":"'$REGION'","analysis":{}}' > "$RESULTS_FILE"

# Function to get current third-party component versions
get_current_versions() {
    local cluster="$1"
    local region="$2"
    
    print_info "Detecting current third-party component versions..." >&2
    
    # Update kubeconfig
    aws eks update-kubeconfig --region "$region" --name "$cluster" >/dev/null 2>&1
    
    # Use simple arrays instead of associative arrays for Bash 3.2 compatibility
    local component_data=""
    
    # Check ingress-nginx
    local ingress_nginx_image=$(kubectl get deployment -n ingress-nginx ingress-nginx-controller -o jsonpath='{.spec.template.spec.containers[0].image}' 2>/dev/null)
    if [[ -n "$ingress_nginx_image" ]]; then
        local ingress_version=$(echo "$ingress_nginx_image" | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' | head -1)
        component_data="${component_data}ingress-nginx:${ingress_version}\n"
        if [[ "$VERBOSE" == "true" ]]; then
            print_info "Found ingress-nginx: $ingress_version" >&2
        fi
    else
        component_data="${component_data}ingress-nginx:not_found\n"
    fi
    
    # Check NVIDIA GPU device plugin
    local gpu_plugin_image=$(kubectl get daemonset -n kube-system nvidia-device-plugin-daemonset -o jsonpath='{.spec.template.spec.containers[0].image}' 2>/dev/null)
    if [[ -n "$gpu_plugin_image" ]]; then
        local gpu_version=$(echo "$gpu_plugin_image" | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' | head -1)
        component_data="${component_data}nvidia-gpu-plugin:${gpu_version}\n"
        if [[ "$VERBOSE" == "true" ]]; then
            print_info "Found NVIDIA GPU plugin: $gpu_version" >&2
        fi
    else
        component_data="${component_data}nvidia-gpu-plugin:not_found\n"
    fi
    
    # Check NodeLocal DNSCache
    local dns_cache_image=$(kubectl get daemonset -n kube-system node-local-dns -o jsonpath='{.spec.template.spec.containers[0].image}' 2>/dev/null)
    if [[ -n "$dns_cache_image" ]]; then
        local dns_version=$(echo "$dns_cache_image" | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' | head -1)
        component_data="${component_data}nodelocal-dns:${dns_version}\n"
        if [[ "$VERBOSE" == "true" ]]; then
            print_info "Found NodeLocal DNS: $dns_version" >&2
        fi
    else
        component_data="${component_data}nodelocal-dns:not_found\n"
    fi
    
    # Output the component data
    echo -e "$component_data" | grep -v '^$'
}

# Function to get compatibility information
# 
# IMPORTANT: This compatibility matrix is based on manual research and estimates.
# Data sources and limitations:
# 
# 1. ingress-nginx: Based on official Kubernetes compatibility matrix
#    Source: https://github.com/kubernetes/ingress-nginx#supported-versions-table
#    Last updated: Manual research as of script creation
#    Limitation: May not reflect latest compatibility updates
#
# 2. nvidia-gpu-plugin: Based on NVIDIA official documentation
#    Source: https://github.com/NVIDIA/k8s-device-plugin#compatibility
#    Last updated: Manual research as of script creation
#    Limitation: Requires verification against actual NVIDIA driver versions
#
# 3. nodelocal-dns: Based on Kubernetes DNS documentation
#    Source: https://kubernetes.io/docs/tasks/administer-cluster/nodelocaldns/
#    Last updated: Manual research as of script creation
#    Limitation: Compatibility depends on CoreDNS version coordination
#
# RECOMMENDATION: Always verify compatibility in test environment before production use
#
get_compatibility_info() {
    local component="$1"
    local eks_version="$2"
    
    case "$component" in
        "ingress-nginx")
            # Based on https://github.com/kubernetes/ingress-nginx#supported-versions-table
            # These are conservative estimates - always verify in test environment
            case "$eks_version" in
                "1.27") echo "v1.6.0 v1.10.99 v1.8.4" ;;  # min max recommended
                "1.28") echo "v1.7.0 v1.10.99 v1.9.6" ;;
                "1.29") echo "v1.8.0 v1.11.99 v1.10.1" ;;
                "1.30") echo "v1.9.0 v1.11.99 v1.11.1" ;;
                *) echo "unknown unknown unknown" ;;
            esac
            ;;
        "nvidia-gpu-plugin")
            # Based on https://github.com/NVIDIA/k8s-device-plugin#compatibility
            # CRITICAL: Also depends on NVIDIA driver version compatibility
            case "$eks_version" in
                "1.27") echo "v0.12.0 v0.15.99 v0.14.5" ;;
                "1.28") echo "v0.13.0 v0.15.99 v0.14.5" ;;
                "1.29") echo "v0.14.0 v0.16.99 v0.15.0" ;;
                "1.30") echo "v0.15.0 v0.16.99 v0.15.0" ;;
                *) echo "unknown unknown unknown" ;;
            esac
            ;;
        "nodelocal-dns")
            # Based on Kubernetes DNS documentation and CoreDNS compatibility
            # NOTE: Must coordinate with CoreDNS version upgrades
            case "$eks_version" in
                "1.27") echo "v1.21.0 v1.23.99 v1.22.28" ;;
                "1.28") echo "v1.22.0 v1.23.99 v1.22.28" ;;
                "1.29") echo "v1.22.0 v1.24.99 v1.23.0" ;;
                "1.30") echo "v1.23.0 v1.24.99 v1.23.0" ;;
                *) echo "unknown unknown unknown" ;;
            esac
            ;;
        *)
            echo "unknown unknown unknown"
            ;;
    esac
}

# Version comparison function
version_compare() {
    local version1="$1"
    local version2="$2"
    
    # Remove 'v' prefix for comparison
    local v1=$(echo "$version1" | sed 's/^v//')
    local v2=$(echo "$version2" | sed 's/^v//')
    
    # Use sort -V for version comparison
    if [[ "$v1" == "$v2" ]]; then
        echo "0"  # equal
    elif [[ "$(printf '%s\n%s' "$v1" "$v2" | sort -V | head -n1)" == "$v1" ]]; then
        echo "-1" # v1 < v2
    else
        echo "1"  # v1 > v2
    fi
}

# Check compatibility function
check_compatibility() {
    local component="$1"
    local current_version="$2"
    local eks_version="$3"
    
    if [[ "$current_version" == "not_found" ]]; then
        echo "NOT_INSTALLED"
        return
    fi
    
    local compat_info=$(get_compatibility_info "$component" "$eks_version")
    local min_version=$(echo "$compat_info" | awk '{print $1}')
    local max_version=$(echo "$compat_info" | awk '{print $2}')
    local recommended_version=$(echo "$compat_info" | awk '{print $3}')
    
    if [[ "$min_version" == "unknown" ]]; then
        echo "NEEDS_ANALYSIS"
        return
    fi
    
    local min_compare=$(version_compare "$current_version" "$min_version")
    local max_compare=$(version_compare "$current_version" "$max_version")
    
    if [[ $min_compare -ge 0 && $max_compare -le 0 ]]; then
        echo "COMPATIBLE"
    else
        echo "UPGRADE_REQUIRED"
    fi
}

# Get risk level function
get_risk_level() {
    local component="$1"
    local current_version="$2"
    local target_version="$3"
    
    if [[ "$current_version" == "not_found" ]]; then
        echo "N/A"
        return
    fi
    
    # Extract version numbers for comparison
    local current_major=$(echo "$current_version" | sed 's/^v//' | cut -d. -f1)
    local current_minor=$(echo "$current_version" | sed 's/^v//' | cut -d. -f2)
    local target_major=$(echo "$target_version" | sed 's/^v//' | cut -d. -f1)
    local target_minor=$(echo "$target_version" | sed 's/^v//' | cut -d. -f2)
    
    # Component-specific risk assessment
    case "$component" in
        "ingress-nginx")
            if [[ $((target_minor - current_minor)) -gt 2 ]]; then
                echo "MEDIUM"
            else
                echo "LOW"
            fi
            ;;
        "nvidia-gpu-plugin")
            if [[ $((target_minor - current_minor)) -gt 1 ]]; then
                echo "HIGH"
            else
                echo "MEDIUM"
            fi
            ;;
        "nodelocal-dns")
            if [[ $((target_minor - current_minor)) -gt 1 ]]; then
                echo "HIGH"
            else
                echo "MEDIUM"
            fi
            ;;
        *)
            echo "UNKNOWN"
            ;;
    esac
}

# Add analysis result function
add_analysis_result() {
    local eks_version="$1"
    local component_name="$2"
    local current_version="$3"
    local compatibility_status="$4"
    local action="$5"
    local target_version="$6"
    local reason="$7"
    local risk_level="$8"
    
    jq --arg eks "$eks_version" --arg component "$component_name" --arg current "$current_version" \
       --arg status "$compatibility_status" --arg action "$action" --arg target "$target_version" \
       --arg reason "$reason" --arg risk "$risk_level" \
       '.analysis[$eks] += [{
         component: $component,
         current_version: $current,
         compatibility_status: $status,
         action: $action,
         target_version: $target,
         reason: $reason,
         risk_level: $risk
       }]' "$RESULTS_FILE" > "$RESULTS_FILE.tmp" && mv "$RESULTS_FILE.tmp" "$RESULTS_FILE"
}

# Analyze compatibility for a specific EKS version
analyze_compatibility() {
    local target_eks_version="$1"
    local cluster="$2"
    local region="$3"
    
    print_info "Analyzing third-party component compatibility for EKS $target_eks_version"
    echo "=================================================================="
    
    # Get current component versions
    local component_data=$(get_current_versions "$cluster" "$region")
    
    if [[ -z "$component_data" ]]; then
        print_error "Failed to retrieve component versions"
        return 1
    fi
    
    local upgrade_required=()
    local keep_current=()
    local not_installed=()
    
    while IFS=':' read -r component current_version; do
        if [[ -z "$component" ]]; then
            continue
        fi
        
        local compatibility=$(check_compatibility "$component" "$current_version" "$target_eks_version")
        local compat_info=$(get_compatibility_info "$component" "$target_eks_version")
        local min_version=$(echo "$compat_info" | awk '{print $1}')
        local max_version=$(echo "$compat_info" | awk '{print $2}')
        local recommended_version=$(echo "$compat_info" | awk '{print $3}')
        
        case "$compatibility" in
            "COMPATIBLE")
                print_compatible "$component $current_version is compatible with EKS $target_eks_version ($min_version~$max_version)"
                keep_current+=("$component:$current_version")
                add_analysis_result "$target_eks_version" "$component" "$current_version" "COMPATIBLE" "KEEP" "-" "Current version is within compatibility range ($min_version~$max_version)" "LOW"
                ;;
            "UPGRADE_REQUIRED")
                local risk_level=$(get_risk_level "$component" "$current_version" "$recommended_version")
                print_upgrade_required "$component $current_version is NOT compatible with EKS $target_eks_version (requires $min_version~$max_version)"
                print_info "  → Recommended upgrade to: $recommended_version (Risk: $risk_level)"
                upgrade_required+=("$component:$current_version:$recommended_version:$risk_level")
                add_analysis_result "$target_eks_version" "$component" "$current_version" "UPGRADE_REQUIRED" "UPGRADE" "$recommended_version" "Current version is outside compatibility range, requires $min_version~$max_version" "$risk_level"
                ;;
            "NOT_INSTALLED")
                print_warning "$component is not installed in the cluster"
                not_installed+=("$component")
                add_analysis_result "$target_eks_version" "$component" "not_found" "NOT_INSTALLED" "OPTIONAL_INSTALL" "$recommended_version" "Component not currently installed" "N/A"
                ;;
            "NEEDS_ANALYSIS")
                print_warning "$component $current_version compatibility with EKS $target_eks_version needs manual analysis"
                add_analysis_result "$target_eks_version" "$component" "$current_version" "NEEDS_ANALYSIS" "MANUAL_CHECK" "-" "Compatibility matrix not available, manual analysis required" "UNKNOWN"
                ;;
        esac
    done <<< "$component_data"
    
    # Generate summary
    echo ""
    print_info "=== THIRD-PARTY COMPONENT SUMMARY FOR EKS $target_eks_version ==="
    
    if [[ ${#keep_current[@]} -gt 0 ]]; then
        echo ""
        print_success "Components to KEEP (${#keep_current[@]}):"
        for item in "${keep_current[@]}"; do
            IFS=':' read -r component version <<< "$item"
            echo "  ✅ $component: $version"
        done
    fi
    
    if [[ ${#upgrade_required[@]} -gt 0 ]]; then
        echo ""
        print_warning "Components to UPGRADE (${#upgrade_required[@]}):"
        for item in "${upgrade_required[@]}"; do
            IFS=':' read -r component current target risk <<< "$item"
            echo "  ❌ $component: $current → $target (Risk: $risk)"
        done
    fi
    
    if [[ ${#not_installed[@]} -gt 0 ]]; then
        echo ""
        print_info "Components NOT INSTALLED (${#not_installed[@]}):"
        for component in "${not_installed[@]}"; do
            echo "  ➖ $component: Not currently installed"
        done
    fi
    
    echo ""
    print_info "Risk Assessment:"
    echo "  - LOW: Minor version upgrade, minimal configuration impact"
    echo "  - MEDIUM: Moderate version jump, may affect some configurations"
    echo "  - HIGH: Major version upgrade or critical component, significant review needed"
    
    # Generate upgrade recommendations
    if [[ ${#upgrade_required[@]} -gt 0 ]]; then
        echo ""
        print_info "=== UPGRADE RECOMMENDATIONS ==="
        local recommendations_file="$OUTPUT_DIR/upgrade-recommendations-eks-$target_eks_version.md"
        cat > "$recommendations_file" << EOF
# Third-Party Component Upgrade Recommendations for EKS $target_eks_version

## Components Requiring Upgrades

EOF
        
        for item in "${upgrade_required[@]}"; do
            IFS=':' read -r component current target risk <<< "$item"
            cat >> "$recommendations_file" << EOF
### $component
- **Current Version**: $current
- **Target Version**: $target
- **Risk Level**: $risk
- **Upgrade Timing**: 
EOF
            
            case "$component" in
                "ingress-nginx")
                    cat >> "$recommendations_file" << EOF
  - Can be upgraded independently of EKS version
  - Recommended during maintenance window
  - Use rolling update strategy
- **Verification Steps**:
  - Test HTTP/HTTPS traffic routing
  - Verify SSL termination
  - Check custom configurations
EOF
                    ;;
                "nvidia-gpu-plugin")
                    cat >> "$recommendations_file" << EOF
  - Upgrade during data plane upgrade (requires node restart)
  - Schedule during maintenance window
  - Verify NVIDIA driver compatibility first
- **Verification Steps**:
  - Check GPU resource allocation
  - Test GPU workload scheduling
  - Verify CUDA runtime functionality
EOF
                    ;;
                "nodelocal-dns")
                    cat >> "$recommendations_file" << EOF
  - Coordinate with CoreDNS upgrade
  - Use gradual rollout strategy
  - Monitor DNS resolution during upgrade
- **Verification Steps**:
  - Test internal service DNS resolution
  - Test external domain resolution
  - Check DNS cache hit rates
EOF
                    ;;
            esac
            
            echo "" >> "$recommendations_file"
        done
        
        print_success "Upgrade recommendations generated: $recommendations_file"
    fi
}

# Main execution
main() {
    # Check if jq is installed
    if ! command -v jq &> /dev/null; then
        print_error "jq is required but not installed. Please install jq first."
        exit 1
    fi
    
    # Check kubectl
    if ! command -v kubectl &> /dev/null; then
        print_error "kubectl is required but not installed. Please install kubectl first."
        exit 1
    fi
    
    # Check AWS CLI
    if ! command -v aws &> /dev/null; then
        print_error "AWS CLI is required but not installed. Please install AWS CLI first."
        exit 1
    fi
    
    # Test AWS credentials
    if ! aws sts get-caller-identity &> /dev/null; then
        print_error "AWS credentials not configured or invalid. Please configure AWS CLI first."
        exit 1
    fi
    
    # Analyze single target version
    if [[ -n "$TARGET_VERSION" ]]; then
        analyze_compatibility "$TARGET_VERSION" "$CLUSTER_NAME" "$REGION"
    fi
    
    # Analyze upgrade path
    if [[ -n "$UPGRADE_PATH" ]]; then
        IFS=',' read -ra VERSIONS <<< "$UPGRADE_PATH"
        for version in "${VERSIONS[@]}"; do
            version=$(echo "$version" | xargs) # trim whitespace
            if [[ "$version" =~ ^[0-9]+\.[0-9]+$ ]]; then
                echo ""
                echo "######################################################"
                analyze_compatibility "$version" "$CLUSTER_NAME" "$REGION"
                echo "######################################################"
            else
                print_warning "Skipping invalid version format: $version"
            fi
        done
    fi
    
    # Generate final report
    print_info "Analysis complete. Results saved to: $OUTPUT_DIR"
    
    if [[ "$FORMAT" == "json" ]]; then
        print_info "JSON report: $RESULTS_FILE"
    elif [[ "$FORMAT" == "yaml" ]]; then
        local yaml_file="$OUTPUT_DIR/third-party-compatibility.yaml"
        if command -v yq &> /dev/null; then
            yq eval "$RESULTS_FILE" > "$yaml_file"
            print_info "YAML report: $yaml_file"
        else
            print_warning "yq not found, YAML output not generated"
        fi
    fi
    
    print_success "Third-party add-on compatibility analysis completed successfully!"
    
    # Generate compatibility data verification guide
    local verification_guide="$OUTPUT_DIR/verify-compatibility-data.md"
    cat > "$verification_guide" << 'EOF'
# Third-Party Compatibility Data Verification Guide

## Current Data Sources and Limitations

The compatibility information in this script is based on manual research and may not be current. Here's how to verify and update the data:

### 1. ingress-nginx Compatibility
**Official Source**: https://github.com/kubernetes/ingress-nginx#supported-versions-table

**Verification Steps**:
```bash
# Check latest releases
curl -s https://api.github.com/repos/kubernetes/ingress-nginx/releases/latest | jq -r '.tag_name'

# Check Kubernetes compatibility in release notes
curl -s https://api.github.com/repos/kubernetes/ingress-nginx/releases | jq -r '.[].body' | grep -i kubernetes
```

### 2. NVIDIA GPU Device Plugin Compatibility
**Official Source**: https://github.com/NVIDIA/k8s-device-plugin#compatibility

**Verification Steps**:
```bash
# Check latest releases
curl -s https://api.github.com/repos/NVIDIA/k8s-device-plugin/releases/latest | jq -r '.tag_name'

# Check compatibility matrix in README
curl -s https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/main/README.md | grep -A 10 -B 10 "Kubernetes"
```

**CRITICAL**: Also verify NVIDIA driver compatibility:
- Check your current driver version: `nvidia-smi`
- Verify against NVIDIA compatibility matrix

### 3. NodeLocal DNSCache Compatibility
**Official Source**: https://kubernetes.io/docs/tasks/administer-cluster/nodelocaldns/

**Verification Steps**:
```bash
# Check Kubernetes DNS documentation
# NodeLocal DNSCache compatibility is closely tied to CoreDNS versions
# Verify your CoreDNS version compatibility first

kubectl get deployment -n kube-system coredns -o jsonpath='{.spec.template.spec.containers[0].image}'
```

## Updating Compatibility Data

To update the compatibility matrix in the script:

1. Research the latest compatibility information from official sources
2. Update the `get_compatibility_info()` function in the script
3. Test the updated compatibility ranges in a test environment
4. Document the update date and sources

## Recommended Verification Process

1. **Always test in non-production environment first**
2. **Verify actual component versions in your cluster**
3. **Check for any custom configurations that might affect compatibility**
4. **Monitor component behavior after upgrades**
5. **Keep compatibility data updated regularly**

EOF
    
    print_info "Compatibility data verification guide: $verification_guide"
}

# Function to show current data sources and update recommendations
show_data_sources() {
    cat << 'EOF'
=== COMPATIBILITY DATA SOURCES AND LIMITATIONS ===

IMPORTANT: The compatibility data in this script is based on manual research 
and conservative estimates. It may not reflect the latest compatibility updates.

Data Sources:
1. ingress-nginx: https://github.com/kubernetes/ingress-nginx#supported-versions-table
2. NVIDIA GPU Plugin: https://github.com/NVIDIA/k8s-device-plugin#compatibility  
3. NodeLocal DNS: https://kubernetes.io/docs/tasks/administer-cluster/nodelocaldns/

Recommendations:
- Always verify compatibility in test environment before production use
- Check official documentation for latest compatibility information
- Update the compatibility matrix in this script based on your testing results
- Consider the specific versions currently deployed in your environment

To see detailed verification steps, run the analysis and check the generated 
verification guide in the output directory.

EOF
}

# Add data sources option to help
if [[ "$1" == "--show-sources" ]]; then
    show_data_sources
    exit 0
fi

# Run main function
main "$@"